package com.akuma.common.util;

import com.akuma.redmine.config.Config;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by akuma on 2016/10/12.
 *
 * @author akuma
 */
public class HttpRequest {

    public static String get(String url, Map<String, String> params) throws URISyntaxException, IOException {
        HttpClient httpclient = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (String key : params.keySet()) {
                builder.setParameter(key, params.get(key));
            }
        }
        URI uri = builder.build();
        HttpGet request = new HttpGet(uri);
        request.setHeader("Content-Type", "text/html");


        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();
        String returnMsg = "response is null";
        if (entity != null) {
            returnMsg = EntityUtils.toString(entity);
        }
        return returnMsg;
    }

    public static String postJson(String json, String url, Map<String, String> params) throws URISyntaxException, IOException {
        HttpClient httpclient = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (String key : params.keySet()) {
                builder.setParameter(key, params.get(key));
            }
        }
        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json");
        System.out.println(json);
        request.setEntity(new StringEntity(json));
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();
        String returnMsg = null;
        if (entity != null) {
            returnMsg = EntityUtils.toString(entity);
        }
        return returnMsg;
    }
}
